package DAO;

import Entidad.Movie;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;

public class DAO_Movie {
    
    public String create(Movie pelicula, EntityManager em) {
        em.getTransaction().begin();
        try {
            em.persist(pelicula);
            em.getTransaction().commit();
            return "Succes";
        } catch (Exception e) {
            System.out.println(e);
            em.getTransaction().rollback();
            return "Fail";
        }
    }
    
    public String delete(String nombre, EntityManager em) {
        em.getTransaction().begin();
        try {
            Query q = em.createQuery("DELETE FROM movie u WHERE u.name ='"+ nombre +"'");
            q.executeUpdate();
            em.getTransaction().commit();
            return "Succes";
        } catch (Exception e) {
            System.out.println(e);
            em.getTransaction().rollback();
            return "Fail";
        }
    }
    
    public void update(Movie antiguo, Movie nuevo, EntityManager em) {
        em.getTransaction().begin();
        try {
            Query q = em.createQuery("UPDATE Movie m SET m.Name = '"+ nuevo.getName() +"', m.Year = '"+ 
                                    nuevo.getYear() +"', m.Cover = '"+ nuevo.getCover() +"', m.PlotKeywords = '"+ 
                                    nuevo.getPlotKeywords() +"', m.Genre = '"+ nuevo.getGenre() +"', m.Rating = '"+
                                    nuevo.getRating() +"', m.Duration = '"+ nuevo.getDuration() +"', m.AvailableForRental = '"+
                                    nuevo.getAvailableForRental()+ "', m.AvailableForPurchase = '"+nuevo.getAvailableForPurchase()+
                                    "' WHERE m.Name = '"+ antiguo.getName());
            
            q.executeUpdate();
            em.getTransaction().commit();
        } catch (Exception e) {
            System.out.println(e);
            em.getTransaction().rollback();
        }
    }
    
    public Movie buscarMovie(String nombre, EntityManager em){
        try{
            Query q = em.createQuery("Select u from Movie as u where u.Name = '"+ nombre +"'");
            return (Movie)q.getSingleResult();
        }catch(Exception e){
            System.out.println(e);
            return null;
        }
    }
    
    public List<Movie> buscar_pelicula(String busqueda, EntityManager em){
        try{
            Query q = em.createQuery("SELECT u FROM Movie as u WHERE u.name = '"+ busqueda +"' OR u.year = '"+ busqueda +
                    "' OR u.PlotKeyWords = '"+ busqueda +"' OR u.genre = '"+ busqueda +"' OR u.rating = '"+ busqueda +
                    "' OR u.name = '"+ busqueda +"' OR ");
            return q.getResultList();
        }
        catch(Exception e){
            System.out.println(e);
            return null;
        }
    }
 }
